package com.example.weatherreport.net;

import android.util.Log;

import com.example.weatherreport.bean.Weather;
import com.example.weatherreport.net.callback.WeatherCallback;
import com.google.gson.Gson;

import org.jetbrains.annotations.NotNull;

import java.io.IOException;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class WeatherHelper {
    private static final String TAG = "WeatherHelper";

    public static void queryWeather(final WeatherCallback callback) {
        String url = "https://tianqiapi.com/api?version=v6&appid=28369561&appsecret=kp2B15Nq";
        //发出网络请求
        OkHttpClient client = new OkHttpClient();
        Request request = new Request.Builder()
                .url(url)
                .addHeader("name", "value")//如过服务端有必要，可以在这边添加头部信息
                .build();
        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(@NotNull Call call, @NotNull IOException e) {
                Log.e(TAG, "onFailure: ", e);
            }

            @Override
            public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
                final String responseBody = response.body().string();
                final Weather weather = new Gson().fromJson(responseBody, Weather.class);
                if (callback != null && weather != null) {
                    callback.onResult(weather);
                }
            }
        });
    }
}
